package classfile

type ConstantPool []ConstantInfo


func readConstantPool(reader *ClassReader) ConstantPool {
	count := int(reader.ReadUint16())
	cp := make([]ConstantInfo, count)
	for i := 1; i < count; i++ {
		cp[i] = readConstantInfo(reader, cp)
		switch cp[i].(type) {
		case *ConstantLongInfo, *ConstantDoubleInfo:
			i++ // 占两个位置
			break
		}
	}
	return cp
}

func (self ConstantPool)getUtf8(index uint16) string {
	info := self.getConstantInfo(index)
	utf8Info := info.(*ConstantUtf8Info)
	return utf8Info.str
}

func (self ConstantPool)getClassName(index uint16) string {
	info := self.getConstantInfo(index)
	classInfo := info.(*ConstantClassInfo)
	return self.getUtf8(classInfo.nameIndex)
}

func (self ConstantPool)getConstantInfo(index uint16) ConstantInfo {
	if cpInfo := self[index]; cpInfo != nil {
		return cpInfo
	}
	panic("Invalid constant pool index!")
}

func (self ConstantPool)getNameAndType(index uint16) (string, string) {
	constantInfo := self.getConstantInfo(index)
	ntInfo := constantInfo.(*ConstantNameAndTypeInfo)
	name := self.getUtf8(ntInfo.nameIndex)
	_type := self.getUtf8(ntInfo.descriptorIndex)
	return name, _type
}
